/**
 * 
 */
package org.vsg.stock.extension.processor;

import java.text.DecimalFormat;
import java.util.List;

import javax.annotation.Resource;

import org.vsg.stock.basic.domain.StockDailyLine;
import org.vsg.stock.extension.service.StockHistoryService;
import org.vsg.stock.extension.vo.HistoryPatternStock;

/**
 * @author vison
 *
 */
public class SimilaritiesPatternFilterProcessor extends
		AbstractPatternFilterProcessor {
	
	private DecimalFormat df = new DecimalFormat("##0.0000");
	
	@Resource
	private StockHistoryService stockHistoryService;

	@Override
	public double calculateCloseValue(List<StockDailyLine> stockDailyLines,
			List<HistoryPatternStock> hisPatternStockList) {
		// caclulate the compaire vol value
		String currentStockCode = stockDailyLines.get(0).getStockCode();
		// --- get the pattern value ---
		List<HistoryPatternStock> currentHisPatternStock = stockHistoryService.getAbstractShapePatternData(stockDailyLines, 5);
		
		if (checkSamePatternStock(currentHisPatternStock,hisPatternStockList)) {
			return 0;
		}
		
		double[] ratioValues = new double[currentHisPatternStock.size()];
		double totalDisc = 0;
		HistoryPatternStock currentHps = null;
		HistoryPatternStock otherHps = null;
		for (int i = 0 ; i < ratioValues.length ; i++) {
			currentHps = currentHisPatternStock.get(i);
			otherHps = hisPatternStockList.get(i);
			ratioValues[i] = currentHps.getRatioValue() - otherHps.getRatioValue();
			totalDisc+= Math.abs( ratioValues[i] );

		}
		// 100 persent = 20
		double returnValue = (20 - totalDisc) * 5;
		
		if (returnValue > 80) {
			return Double.parseDouble( df.format(returnValue ) );
		}
		
		return 0;
	}
	
	
	private boolean checkSamePatternStock(List<HistoryPatternStock> currentHisPatternStock , List<HistoryPatternStock> otherHisPatternStock) {
		HistoryPatternStock firstCurrent = currentHisPatternStock.get(0);
		HistoryPatternStock firstOther = otherHisPatternStock.get(0);
		HistoryPatternStock lastCurrent = currentHisPatternStock.get(currentHisPatternStock.size()-1);
		HistoryPatternStock lastOther = otherHisPatternStock.get(otherHisPatternStock.size()-1);
		
		if (firstCurrent.getCode().equalsIgnoreCase(firstOther.getCode() )
			&& 	firstCurrent.getStartDate().compareTo( firstOther.getStartDate() ) == 0
			&& 	firstCurrent.getEndDate().compareTo( firstOther.getEndDate() ) == 0
			&& 	lastCurrent.getStartDate().compareTo( lastOther.getStartDate() ) == 0
			&& 	lastCurrent.getEndDate().compareTo( lastOther.getEndDate() ) == 0
		) {
			return true;			
		} 
		
		return false;
	}

	
	
}
